package wcg;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.CharBuffer;
import java.text.DecimalFormat;

import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.Component;
import javax.swing.JCheckBox;
import java.awt.Font;
import java.awt.Frame;
import javax.swing.border.MatteBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;

/**
 * ヘルプウィンドウ
 * @author Toshiharu Ikeda <ikeda.104@gmail.com>
 *
 */
public class helpWindow extends JDialog {
	JTextPane textPaneMain ;
	//JEditorPane textPaneMain ;
	JCheckBox chckbxCheckBoxCaseSensitive;
	JScrollPane scrollPane;
	
	public helpWindow(){
		setIconImage(Toolkit.getDefaultToolkit().getImage(helpWindow.class.getResource("/images/winchkg3-icon.png")));
		
		scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		textPaneMain = new JTextPane();
		textPaneMain.setPreferredSize(new Dimension(400, 19));
	
		textPaneMain.setFont(new Font("Monospaced", Font.PLAIN, 12));
		textPaneMain.setEditable(false);
		textPaneMain.setBackground(new Color(255, 250, 240));
		
		setTabPosition();
		
		scrollPane.setViewportView(textPaneMain);
		
		//scrollPane.setViewportView(textPaneMain);
		//scrollPane.add(textPaneMain);
		
		JPanel panel = new JPanel();
		panel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
		scrollPane.setColumnHeaderView(panel);
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		
		JLabel lblFind = new JLabel("Find >");
		lblFind.setIcon(new ImageIcon(helpWindow.class.getResource("/images/magnifier.png")));
		panel.add(lblFind);
		
		textFieldFinid = new JTextField();
		textFieldFinid.setToolTipText("Enter text to find");
		panel.add(textFieldFinid);
		textFieldFinid.setColumns(10);
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1);
		panel_1.setLayout(new GridLayout(1, 0, 0, 0));

		chckbxCheckBoxCaseSensitive = new JCheckBox("Case sensitive");
		
		JButton btnFindUpButton = new JButton("");
		btnFindUpButton.setToolTipText("Find backword");
		btnFindUpButton.setIcon(new ImageIcon(helpWindow.class.getResource("/images/arrow_up.png")));
		btnFindUpButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String find = textFieldFinid.getText();
				if(find.isEmpty()) return;
				doFind(find,false,chckbxCheckBoxCaseSensitive.isSelected());
				
			}
		});
		
		JButton btnFindDownButton = new JButton("");
		btnFindDownButton.setToolTipText("Find forward");
		btnFindDownButton.setIcon(new ImageIcon(helpWindow.class.getResource("/images/arrow_down.png")));
		btnFindDownButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String find = textFieldFinid.getText();
				if(find.isEmpty()) return;
				doFind(find,true,chckbxCheckBoxCaseSensitive.isSelected());
			}
		});
		panel.add(btnFindDownButton);
		panel.add(btnFindUpButton);
		
		panel.add(chckbxCheckBoxCaseSensitive);
		
		addComponentListener(new ComponentAdapter_JFrame());  //フレームにComponentListenerを登録する

		//showHelp("help_en.txt");
	}
	class ComponentAdapter_JFrame extends ComponentAdapter{
	    public void componentResized(ComponentEvent e) {              //フレームのサイズが変更されたとき
	    	getContentPane().validate();
	    }
	}
	private void setTabPosition() {
		// タブ位置をセットする。
		FontMetrics fm = textPaneMain.getFontMetrics(textPaneMain.getFont());
		int charWidth = fm.charWidth('m');
		int tabLength = charWidth * 4;
		TabStop[] tabs = new TabStop[10];
		for(int j=0;j<tabs.length;j++) {
		  tabs[j] = new TabStop((j+1)*tabLength);
		}
		TabSet tabSet = new TabSet(tabs);
		SimpleAttributeSet attrs = new SimpleAttributeSet();
		StyleConstants.setTabSet(attrs, tabSet);
		int l = textPaneMain.getDocument().getLength();
		textPaneMain.getStyledDocument().setParagraphAttributes(0, l, attrs, false);
	}
	helpWindow(int code){
		//showHelp("help.txt");
	}
	/**
	 * 検索
	 * @param keyword
	 * @param down
	 * @param caseSensitive
	 */
	private void doFind(String keyword,boolean down,boolean caseSensitive){
		if(!caseSensitive){
			keyword = keyword.toUpperCase();
		}
		//jtextAreaの改行コードを合わせる（これをしないと文字位置を見誤る）
		String text = textPaneMain.getText().replaceAll("\r\n", "\n");
		if(!caseSensitive){
			text = text.toUpperCase();
		}
		//現在のカーソル位置から最後までの文字列（下へ検索用）
		String word; 
		if(down){
			word = text.substring(textPaneMain.getSelectionEnd(), text.length());
		}
		//現在のカーソル位置から最後までの文字列（上へ検索用）
		else {
			word = text.substring(0, textPaneMain.getSelectionStart());
		}
		//検索したい文字が見つからなければ
		if(word.indexOf(keyword) < 0){
			//String Mess.setText(keyword+"は見つかりませんでした");
			//textPaneMain.requestFocus(true);
			return;
		}
		//検索した文字列を選択する（下へ検索用）
		if(down){
			textPaneMain.setSelectionStart(textPaneMain.getSelectionEnd() + word.indexOf(keyword));
			textPaneMain.setSelectionEnd(textPaneMain.getSelectionStart() + keyword.length());
		}
		//検索した文字列を選択する（上へ検索用）
		else{
			textPaneMain.setSelectionStart(word.lastIndexOf(keyword));
			textPaneMain.setSelectionEnd(textPaneMain.getSelectionStart() + keyword.length());
		}
		textPaneMain.requestFocus(true);	
	}
	/**
	 * テキストエリア
	 */
	private JTextArea   ta;
	/**
	 * スクロールペイン
	 */
	private JScrollPane sp; 
	/**
	 * 検索テキストフィールド
	 */
	private JTextField textFieldFinid;
	
	
	/**
	 * ヘルプの表示
	 * @param txtFile
	 */
	public void showHelp(String txtFile){
		//getContentPane().setLayout(new GridLayout(1,1,0,0));
		String str = "";
		if(txtFile.compareToIgnoreCase("systeminfo")==0){
			this.setTitle("systeminfo");
			ta = new JTextArea(str, 10, 100);
			str = new String("---- System Information ------------------------------------\n");
			str += getMemoryInfo();
			str +=       new String("------------------------------------------------------------\n");
			ta.setText(str);
		}
		else{
			this.setTitle("winchkg-help");
			try {
				InputStream is = getClass().getResourceAsStream(txtFile);
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String line;
				int  invalid = 0;
				
				while((line = reader.readLine()) != null) {
					if(line.startsWith("$$$-")){
						String ec = line.substring(4,line.length());
						if(ec != null){
							ec = ec.trim();
							if(!winchkgProperty.isAvailable(ec)){
								invalid++;
							}
						}
					}
					else if(line.startsWith("-$$$")){
						if(invalid>0) invalid--;
					}
					else if(invalid==0){
						str += new String(line);
						str += "\n";
					}
				}
				textPaneMain.setText(str);
				Dimension d = new Dimension(textPaneMain.getPreferredSize());
				
				textPaneMain.setSize(new Dimension(d.width+50,600));
				textPaneMain.validate();
				
				//setVisible(true);
				Thread th = new Thread(new delayTask());
				th.start();

			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	private class delayTask extends Thread{
		public void run(){
			try {
				sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			showTop();
		}
	}
	private void showTop(){
		//sp.getVerticalScrollBar().setValue(0);
		textPaneMain.setSelectionStart(0);
		textPaneMain.setSelectionEnd(0);
		textPaneMain.requestFocus(true);	
	}
	public static String getMemoryInfo() {
	    DecimalFormat f1 = new DecimalFormat("#,### MB");
	    DecimalFormat f2 = new DecimalFormat("##.#");
	    long free = Runtime.getRuntime().freeMemory() / (1024*1024);
	    long total = Runtime.getRuntime().totalMemory() / (1024*1024);
	    long max = Runtime.getRuntime().maxMemory() / (1024*1024);
	    long used = total - free;
	    double ratio = (used * 100 / (double)total);
	    String info = 
	    "JAVA Memory Information\n" +
	    "       Max=" + f1.format(max) +"\n" + 
	    "     Total=" + f1.format(total) + "\n" +
	    "     Using=" + f1.format(used) + " (" + f2.format(ratio) + "%)\n";
	    
	    try{
		    info += "\n"+"JAVA Runtime Environment Version\n" + "       " + System.getProperty("java.version")+"\n";
		    //info += "JAVA VM implement Version\n" + "       " + System.getProperty("java.vm.version")+"\n";
	    }catch(SecurityException e){
	    	
	    }
	    return info;
	}
	
	
	
}
